package com.zs.demo.common.exception;


import com.zs.demo.common.response.ResponseData;
import com.zs.demo.common.response.CommonStatus;
import lombok.extern.log4j.Log4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/* @Desc: 全局异常拦截
 * @author:zhengs  
 * @Time: 2018/11/20 10:08
 * @Copyright: © zhengs 版权所有  
 * @Warning: 本内容仅限于本公司内部传阅,禁止外泄或用于其它商业目的
 */
@ControllerAdvice(basePackages = {"com.zs.demo"})
@Log4j
public class GlobalExceptionHandler {
    /* @Desc:参数校验异常拦截
     * @author:zhengs
     * @Time: 2018/11/20 14:53
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseData handle(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        String msg = CommonStatus.WEB_PARAM_FAIL.msg;
        if(result.hasErrors()){
            List<ObjectError> errors = result.getAllErrors();
            msg = errors.get(0).getDefaultMessage();
        }

        return new ResponseData(CommonStatus.WEB_PARAM_FAIL.status,msg);
    }

    /* @Desc:自定义异常拦截
     * @author:zhengs  
     * @Time: 2018/11/20 14:53
     * @param e
     * @return
     */
    @ExceptionHandler(value = RestException.class)
    @ResponseBody
    public ResponseData handle(RestException e){
        if(e.getE()!=null){
            e.printStackTrace();
        }

        return new ResponseData(e.getStatus(),e.getMsg());
    }

    /* @Desc:数据库异常拦截
     * @author:zhengs
     * @Time: 2018/11/20 14:53
     * @param e
     * @return
     */
    @ExceptionHandler(value = DataIntegrityViolationException.class)
    @ResponseBody
    public ResponseData handle(DataIntegrityViolationException e){
        return new ResponseData(CommonStatus.DB_PARAM_FAIL);
    }

    /* @Desc:未知异常拦截
     * @author:zhengs  
     * @Time: 2018/11/20 14:54
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData handle(Exception e){
        e.printStackTrace();
        return new ResponseData(CommonStatus.INNER_ERROR);
    }
}